/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.boot.starter.middleware.config;

import io.iec.edp.caf.app.manager.classloader.CAFClassLoader;
import io.iec.edp.caf.boot.starter.middleware.spi.utils.ClassLoaderResolverUtils;
import io.iec.edp.caf.commons.runtime.CafEnvironment;
import io.iec.edp.caf.commons.utils.JarUtil;

import lombok.var;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import sun.misc.URLClassPath;

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 扩展Spring应用Runner，在较早的时机（environment可以读取之后、Bean加载执行）把servlet加到列表
 * @author wangyandong
 */
@Deprecated
public class ServletSpringApplicationRunListener implements SpringApplicationRunListener {

    public ServletSpringApplicationRunListener(SpringApplication application, String[] args) {

    }

    /**
     * Called once the environment has been prepared, but before the
     * {@link ApplicationContext} has been created.
     * @param environment the environment
     */
    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        //当需要配置中心时，此值不为null
        var loaded = environment.getProperty("caf.config.client");
        if (loaded != null) {
            return;
        }

        //如果启动脚本中没有相应参数，则在此处进行加载
        boolean startMidWithYaml = System.getProperty("middleware.servlet", "none").equalsIgnoreCase("none");
        if(!startMidWithYaml){
            return;
        }

        //读取server.container，将其加入到classLoader中
        var container = environment.getProperty("server.container", "tomcat");
        Path path = Paths.get(CafEnvironment.getStartupPath(), "middleware", "servlet", container);
        URL[] urls = JarUtil.getJarPathFromDirPaths(path.toString());
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        ClassLoaderResolverUtils.addUrl(cl,urls);
        //并行启动时，将URL加入平台底座
//        if( cl instanceof PlatformClassloader){
//            ((PlatformClassloader)cl).addPlatformURL(urls);
//        }else if(cl instanceof CAFClassLoader){
//            //非并行启动时，将URL加入CAFClassLoader的父中
//            CAFClassLoader cafClassLoader = (CAFClassLoader)cl;
//            this.addUrl((LaunchedURLClassLoader)cafClassLoader.getParent(),urls);
//        }
    }

//    private void addUrl(LaunchedURLClassLoader launchedURLClassLoader, URL[] urls) {
//        URLClassPath ucp;
//        try {
//            Field ucpField = URLClassLoader.class.getDeclaredField("ucp");
//            ucpField.setAccessible(true);
//            ucp = (URLClassPath) ucpField.get(launchedURLClassLoader);
//            for (URL url : urls) {
//                ucp.addURL(url);
//            }
//        } catch (NoSuchFieldException | IllegalAccessException e) {
//            e.printStackTrace();
//        }
//    }
}
